# 使用Python 3.11作为基础镜像
FROM python:3.11-slim

# 设置工作目录
WORKDIR /app

# 安装系统依赖
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    libc-dev \
    && rm -rf /var/lib/apt/lists/*

# 复制requirements.txt并安装依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 复制项目代码
COPY . .

# 创建数据和配置目录（用于持久化映射）
RUN mkdir -p /app/data /app/config

# 设置环境变量
ENV FLASK_APP=app.py
ENV FLASK_ENV=production
ENV HOST=0.0.0.0
ENV PORT=5000
ARG APP_VERSION=dev
ENV APP_VERSION=${APP_VERSION}

# 暴露端口
EXPOSE 5000

# 创建启动脚本（使用heredoc语法避免引号问题）
RUN cat << 'EOF' > /app/start.sh && chmod +x /app/start.sh
#!/bin/sh

# 如果配置文件不存在，创建默认配置
if [ ! -f /app/config/config.json ]; then
    cat << 'JSON' > /app/config/config.json
{
    "douban": {
        "cookie": "",
        "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    },
    "ptskit": {
        "cookie": ""
    },
    "qbittorrent": {
        "host": "localhost",
        "port": 8080,
        "username": "admin",
        "password": "adminadmin"
    },
    "transmission": {
        "host": "localhost",
        "port": 9091,
        "username": "username",
        "password": "password"
    },
    "fnos_media": {
        "server_ip": "localhost",
        "server_port": 5666,
        "username": "username",
        "password": "password",
        "verify_ssl": false
    },
    "emby": {
        "server_url": "localhost",
        "server_port": 8096,
        "api_key": "",
        "user_id": ""
    },
    "tmdb": {
        "api_key": "",
        "proxy_ip": "localhost",
        "proxy_port": "7890"
    },
    "javdb": {
        "cookie": ""
    },
    "app": {
        "data_dir": "/app/data",
        "nfo_dir": "/app/data/nfo_files",
        "image_dir": "/app/data/images"
    }
}
JSON
fi

# 启动Gunicorn服务
exec gunicorn --bind 0.0.0.0:5000 --workers 3 app:app
EOF

# 启动命令
CMD ["/app/start.sh"]
